<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useMindArchiveStore } from '../stores/mindArchiveStore'
import { useContainerStore } from '../stores/containerStore'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

const route = useRoute()

const router = useRouter()
const mindArchiveStore = useMindArchiveStore()
const containerStore = useContainerStore()

// 表单数据
const archiveForm = ref({
  title: '',
  description: '',
  tags: [],
  containerId: '',
  blockingPoint: '',
  notes: ''
})

// 从路由参数获取容器数据并自动填充表单
onMounted(() => {
  const { containerId, containerTitle, containerDescription, containerCategory } = route.query
  
  if (containerId) {
    archiveForm.value.containerId = containerId
    
    // 自动填充标题（基于容器标题）
    if (containerTitle) {
      archiveForm.value.title = `思考：${containerTitle}`
    }
    
    // 自动填充描述（基于容器描述）
    if (containerDescription) {
      archiveForm.value.description = `基于容器「${containerTitle}」的思考\n\n${containerDescription}`
    }
    
    // 自动添加分类标签
    if (containerCategory && !archiveForm.value.tags.includes(containerCategory)) {
      archiveForm.value.tags.push(containerCategory)
    }
  }
})

// 表单规则
const rules = {
  title: [{ required: true, message: '请输入存档标题', trigger: 'blur' }],
  blockingPoint: [{ required: true, message: '请描述当前卡点', trigger: 'blur' }]
}

// 表单引用
const formRef = ref(null)

// 标签选项
const tagOptions = [
  { label: '工作', value: '工作' },
  { label: '学习', value: '学习' },
  { label: '项目', value: '项目' },
  { label: '创意', value: '创意' },
  { label: '问题', value: '问题' },
  { label: '决策', value: '决策' },
  { label: '灵感', value: '灵感' },
  { label: '其他', value: '其他' }
]

// 获取活动中的容器作为预备容器选项
const containerOptions = computed(() => {
  const activeContainers = containerStore.activeContainers
  return activeContainers.map(container => ({
    label: container.title,
    value: container.id
  }))
})

// 创建新的思维存档
function createArchive() {
  formRef.value.validate((valid) => {
    if (valid) {
      const archiveData = {
        ...archiveForm.value,
        notes: archiveForm.value.notes ? [archiveForm.value.notes] : []
      }
      
      mindArchiveStore.createArchive(archiveData)
      
      // 重置表单
      archiveForm.value = {
        title: '',
        description: '',
        tags: [],
        containerId: '',
        blockingPoint: '',
        notes: ''
      }
      
      // 显示成功消息
      ElMessage({
        message: '思维存档创建成功',
        type: 'success'
      })
      
      // 跳转到存档库页面
      router.push('/mind-archive-library')
    }
  })
}

// 自定义标签输入
const customTag = ref('')

function addCustomTag() {
  if (customTag.value && !archiveForm.value.tags.includes(customTag.value)) {
    archiveForm.value.tags.push(customTag.value)
    customTag.value = ''
  }
}
</script>

<template>
  <div class="mind-archive-container">
    <h1 class="page-title">思维存档</h1>
    <p class="page-description">
      记录当前思考的卡点和上下文，便于后续快速恢复思考状态
    </p>
    
    <el-card class="archive-form-card">
      <template #header>
        <div class="card-header">
          <h2>创建思维存档</h2>
        </div>
      </template>
      
      <el-form 
        ref="formRef"
        :model="archiveForm" 
        :rules="rules"
        label-position="top"
      >
        <el-form-item label="存档标题" prop="title">
          <el-input 
            v-model="archiveForm.title" 
            placeholder="简洁描述当前思考的主题"
          />
        </el-form-item>
        
        <el-form-item label="详细描述（可选）" prop="description">
          <el-input 
            v-model="archiveForm.description" 
            type="textarea" 
            placeholder="详细描述当前思考的内容和上下文" 
            :rows="3" 
          />
        </el-form-item>
        
        <el-form-item label="当前卡点" prop="blockingPoint">
          <el-input 
            v-model="archiveForm.blockingPoint" 
            type="textarea" 
            placeholder="描述当前思考遇到的问题或卡点" 
            :rows="3" 
          />
        </el-form-item>
        
        <el-form-item label="关联预备容器（可选）" prop="containerId">
          <el-select 
            v-model="archiveForm.containerId" 
            placeholder="选择关联的时间容器" 
            style="width: 100%"
            clearable
          >
            <el-option 
              v-for="option in containerOptions" 
              :key="option.value" 
              :label="option.label" 
              :value="option.value" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="标签" prop="tags">
          <el-select 
            v-model="archiveForm.tags" 
            placeholder="选择标签" 
            style="width: 100%"
            multiple
            collapse-tags
            collapse-tags-tooltip
          >
            <el-option 
              v-for="option in tagOptions" 
              :key="option.value" 
              :label="option.label" 
              :value="option.value" 
            />
          </el-select>
          
          <div class="custom-tag-input">
            <el-input 
              v-model="customTag" 
              placeholder="添加自定义标签" 
              @keyup.enter="addCustomTag"
            >
              <template #append>
                <el-button @click="addCustomTag">添加</el-button>
              </template>
            </el-input>
          </div>
        </el-form-item>
        
        <el-form-item label="初始备注（可选）" prop="notes">
          <el-input 
            v-model="archiveForm.notes" 
            type="textarea" 
            placeholder="添加初始备注，记录当前的想法" 
            :rows="3" 
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="createArchive" class="submit-button">
            创建存档
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped>
.mind-archive-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.page-title {
  font-size: 28px;
  margin-bottom: 10px;
  color: #303133;
}

.page-description {
  color: #606266;
  margin-bottom: 30px;
}

.archive-form-card {
  margin-bottom: 30px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.custom-tag-input {
  margin-top: 10px;
}

.submit-button {
  width: 100%;
  margin-top: 10px;
}
</style>